<template>
  <div id="app">
    <!-- 登录页面 -->
    <UserLogin v-if="!userStore.isLoggedIn" />
    
    <!-- 主应用 -->
    <el-container v-else>
      <el-header>
        <div class="header-content">
          <div class="logo">
            <h2>涉税信息报送系统</h2>
          </div>
          
          <div class="user-info">
            <el-dropdown @command="handleUserCommand">
              <span class="user-dropdown">
                {{ userStore.userInfo?.realName || userStore.userInfo?.username || '用户' }}
                <el-icon class="el-icon--right">
                  <ArrowDown />
                </el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="profile">个人资料</el-dropdown-item>
                  <el-dropdown-item command="logout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </el-header>
      
      <el-container>
        <el-aside width="200px">
          <el-menu
            :default-active="activeMenu"
            class="el-menu-vertical"
            router>
            <!-- 动态菜单 -->
            <template v-for="menu in accessibleMenus" :key="menu.id">
              <!-- 调试信息 -->
              <div v-if="false" style="font-size: 10px; color: #999; padding: 2px 5px;">
                {{ menu.menuName }} - ID:{{ menu.id }} - Type:{{ menu.type }} - Children:{{ menu.children?.length || 0 }}
              </div>
              
              <!-- 有子菜单的情况 -->
              <el-sub-menu v-if="menu.children && menu.children.length > 0" :index="menu.path || menu.id.toString()">
                <template #title>
                  <el-icon v-if="menu.icon && iconMap[menu.icon]">
                    <component :is="iconMap[menu.icon]" />
                  </el-icon>
                  <span>{{ menu.menuName }}</span>
                </template>
                <el-menu-item 
                  v-for="child in menu.children" 
                  :key="child.id" 
                  :index="child.path"
                  @click="handleMenuClick(child)"
                >
                  <el-icon v-if="child.icon && iconMap[child.icon]">
                    <component :is="iconMap[child.icon]" />
                  </el-icon>
                  <span>{{ child.menuName }}</span>
                </el-menu-item>
              </el-sub-menu>
              
              <!-- 没有子菜单的情况 -->
              <el-menu-item v-else :index="menu.path" @click="handleMenuClick(menu)">
                <el-icon v-if="menu.icon && iconMap[menu.icon]">
                  <component :is="iconMap[menu.icon]" />
                </el-icon>
                <span>{{ menu.menuName }}</span>
              </el-menu-item>
            </template>
          </el-menu>
        </el-aside>
        
        <el-main>
          <router-view />
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useUserStore } from './stores/user'
import { ElMessageBox } from 'element-plus'
import { 
  Upload, 
  Document, 
  List, 
  Setting, 
  House,
  ArrowDown,
  User,
  Lock,
  Menu as MenuIcon
} from '@element-plus/icons-vue'
import UserLogin from './components/UserLogin.vue'

const userStore = useUserStore()
const router = useRouter()
const route = useRoute()

const activeMenu = computed(() => route.path)

// 默认菜单配置（当后端菜单未加载时的备用菜单）
const defaultMenus = [
  {
    id: 1,
    menuName: '主面板',
    path: '/dashboard',
    icon: 'House',
    type: 2  // 菜单类型
  },
  {
    id: 2,
    menuName: '数据导入',
    path: '/upload',
    icon: 'Upload',
    type: 2  // 菜单类型
  },
  {
    id: 3,
    menuName: '税务报送',
    path: '/report',
    icon: 'Document',
    type: 2  // 菜单类型
  },
  {
    id: 4,
    menuName: '系统日志',
    path: '/logs',
    icon: 'List',
    type: 2  // 菜单类型
  },
  {
    id: 6,
    menuName: '测试页面',
    path: '/test',
    icon: 'Setting',
    type: 2  // 菜单类型
  },
  {
    id: 7,
    menuName: 'API测试',
    path: '/api-test',
    icon: 'Setting',
    type: 2  // 菜单类型
  },
  {
    id: 5,
    menuName: '系统管理',
    path: '', // 目录类型不需要路径
    icon: 'Setting',
    type: 1,  // 目录类型
    children: [
      {
        id: 51,
        menuName: '用户管理',
        path: '/users',
        icon: 'User',
        type: 2  // 菜单类型
      },
      {
        id: 52,
        menuName: '用户角色管理',
        path: '/user-roles',
        icon: 'User',
        type: 2  // 菜单类型
      },
      {
        id: 53,
        menuName: '角色管理',
        path: '/roles',
        icon: 'User',
        type: 2  // 菜单类型
      },
      {
        id: 54,
        menuName: '权限管理',
        path: '/permissions',
        icon: 'Lock',
        type: 2  // 菜单类型
      },
      {
        id: 55,
        menuName: '菜单管理',
        path: '/menus',
        icon: 'MenuIcon',
        type: 2  // 菜单类型
      }
    ]
  }
]

// 图标映射
const iconMap = {
  'House': House,
  'Upload': Upload,
  'Document': Document,
  'List': List,
  'Setting': Setting,
  'User': User,
  'Lock': Lock,
  'MenuIcon': MenuIcon
}

// 可访问的菜单
const accessibleMenus = computed(() => {
  const debugInfo = {
    hasBackendMenus: userStore.menus && userStore.menus.length > 0,
    userRole: userStore.userInfo?.role,
    userRoles: userStore.userInfo?.roles,
    isAdmin: userStore.hasRole('ADMIN') || userStore.hasRole('SUPER_ADMIN'),
    hasPermissionManage: userStore.hasPermission('manage'),
    userStoreState: {
      isLoggedIn: userStore.isLoggedIn,
      token: !!userStore.token,
      userInfo: userStore.userInfo,
      permissions: userStore.permissions,
      menus: userStore.menus
    }
  }
  
  console.log('计算可访问菜单:', debugInfo)
  
  // 如果后端菜单已加载，直接使用后端菜单（已经是树形结构）
  if (userStore.menus && userStore.menus.length > 0) {
    console.log('使用后端菜单（已经是树形结构）:', userStore.menus)
    return userStore.menus
  }
  
  // 否则使用默认菜单
  const isAdmin = userStore.hasRole('ADMIN') || userStore.hasRole('SUPER_ADMIN')
  console.log('使用默认菜单，是否管理员:', isAdmin)
  
  if (isAdmin) {
    console.log('返回完整默认菜单（包含系统管理）')
    return defaultMenus
  } else {
    // 普通用户只显示基本菜单（不包含系统管理）
    console.log('返回基本菜单（不包含系统管理）')
    return defaultMenus.filter(menu => menu.id <= 4)
  }
})

// 构建菜单树
const buildMenuTree = (menus) => {
  if (!menus || !Array.isArray(menus)) {
    return []
  }
  
  // 按父级ID分组
  const menuMap = new Map()
  const rootMenus = []
  
  // 先创建所有菜单的映射
  menus.forEach(menu => {
    menuMap.set(menu.id, { ...menu, children: [] })
  })
  
  // 构建树形结构
  menus.forEach(menu => {
    const menuNode = menuMap.get(menu.id)
    if (menu.parentId === null || menu.parentId === 0) {
      rootMenus.push(menuNode)
    } else {
      const parentMenu = menuMap.get(menu.parentId)
      if (parentMenu) {
        parentMenu.children.push(menuNode)
      }
    }
  })
  
  return rootMenus
}

// 处理菜单点击
const handleMenuClick = (menu) => {
  if (menu.path) {
    router.push(menu.path)
  }
}

// 加载用户权限和菜单
const loadUserData = async () => {
  if (userStore.isLoggedIn) {
    try {
      // 并行加载用户权限和菜单
      await Promise.all([
        userStore.getUserPermissions(),
        userStore.getUserMenus()
      ])
    } catch (error) {
      console.error('Failed to load user data:', error)
    }
  }
}

onMounted(() => {
  loadUserData()
})

const handleUserCommand = async (command) => {
  switch (command) {
    case 'profile':
      router.push('/profile')
      break
    case 'logout':
      try {
        await ElMessageBox.confirm('确定要退出登录吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        userStore.logout()
        router.push('/login')
      } catch {
        // 用户取消退出
      }
      break
  }
}

// 临时调试函数
const debugMenuState = () => {
  console.log('=== 菜单状态调试 ===')
  console.log('用户已登录:', userStore.isLoggedIn)
  console.log('用户信息:', userStore.userInfo)
  console.log('用户权限:', userStore.permissions)
  console.log('用户角色:', userStore.userInfo?.roles)
  console.log('后端菜单数据:', userStore.menus)
  console.log('可访问菜单:', accessibleMenus.value)
  
  // 详细分析每个菜单
  if (accessibleMenus.value && accessibleMenus.value.length > 0) {
    console.log('=== 菜单详细分析 ===')
    accessibleMenus.value.forEach((menu, index) => {
      console.log(`菜单 ${index + 1}:`, {
        id: menu.id,
        name: menu.menuName,
        type: menu.type,
        path: menu.path,
        hasChildren: !!menu.children,
        childrenCount: menu.children?.length || 0,
        children: menu.children
      })
    })
  }
  
  // 检查图标映射
  console.log('=== 图标映射检查 ===')
  console.log('可用图标:', Object.keys(iconMap))
  
  // 检查系统管理菜单
  const systemMenu = accessibleMenus.value?.find(m => m.menuName === '系统管理')
  if (systemMenu) {
    console.log('系统管理菜单:', systemMenu)
    console.log('系统管理子菜单:', systemMenu.children)
  } else {
    console.log('未找到系统管理菜单')
  }
}
</script>

<style>
#app {
  height: 100vh;
}

.el-header {
  background-color: #409EFF;
  color: white;
  line-height: 60px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
}

.header-content h1 {
  margin: 0;
}

.user-info {
  display: flex;
  align-items: center;
}

.user-dropdown {
  display: flex;
  align-items: center;
  cursor: pointer;
  color: white;
}

.username {
  margin: 0 8px;
}

.el-aside {
  background-color: #f5f5f5;
}

.el-menu-vertical {
  border-right: none;
}

.el-main {
  padding: 20px;
}
</style>
